import os
import pandas as pd
import pathlib
import sys
import regex as re
project_path = pathlib.Path(os.path.abspath(__file__)).parent.parent.parent
sys.path.append(str(project_path))
from etc.question_answer_config import cypher_sheet_name
from utility.import_log import flog
log = flog(__file__)

class CypherSearch(object):
    def __init__(self, path: str) -> None:
        self.template = pd.read_excel(path, cypher_sheet_name)
        log.info('从Excel中cypher语法配置加载成功')
    def template_match(self, node1: dict, node2: dict) -> str:
        assert type(node1) is dict and 'value' in node1 and 'table' in node1 \
            and 'attr' in node1 and 'is_attr' in node1, "type of node1 is not supported"
        assert type(node2) is dict and 'value' in node2 and 'table' in node2 \
            and 'attr' in node2 and 'is_attr' in node2, "type of node2 is not supported"

        if node1['table'] == node2['table']:
            self.cypher = "match (n:{}) where n.{}='{}' return n.{}".format(node1['table'], 
                            node1['attr'], node1['value'], node2['attr'])
            self.degree_number=0
        else:
            cypher_df = self.template[(self.template['node1']==node1['table']) & 
                                        (self.template['node2']==node2['table'])]
            if cypher_df.empty:
                self.cypher = None
                self.degree_number=None
            else:
                pre_cypher = cypher_df['cypher'].iloc[0]
                map_dict = {"node1_attr":node1['attr'],'node1_value':node1['value'],
                                'node2_attr':node2['attr']}
                self.cypher = pre_cypher.format_map(map_dict)
                node_num=re.findall('\([^\[\]]*\)',pre_cypher)
                degree=re.findall('\[.*(\d+)\]', pre_cypher)
                self.degree_number= len(node_num) - 1 + sum(map(int,degree))-len(degree) if len(degree) else len(node_num)-1
        log.info(f'cypher生成成功:{self.cypher}')
        return self.cypher

if __name__ == "__main__":
    node1 = {'table': 'node', 'attr': 'attr', 'value': 'value', 'is_attr':'is_attr'}
    node2 = {'table': 'node', 'attr': 'attr', 'value': 'value', 'is_attr':'is_attr'}
    path = project_path / 'etc' / 'nodes_relation.xlsx'
    cs = CypherSearch(path)
    print(cs.template_match(node1, node2))